
// 分销产品
package sale
import (
    "fmt"
	"errors"
	"strings"
	"time"
	"dhfshop/models"
	"dhfshop/models/consts"
	"github.com/astaxie/beego/orm"
)

type FenxiaoProduct struct {
    Pid             int64   `orm:"column(pid);pk;auto" json:"pid" form:"pid"`      /* 产品ID */
    CompanyId       int64     `orm:"column(company_id)" json:"company_id" form:"company_id"`    //供应商ID
	CategoryId      int64   `orm:"column(category_id)" json:"category_id" form:"category_id"` /*类目ID  */
    ProductcatId    int64     `orm:"column(productcat_id)" json:"productcat_id" form:"productcat_id"`          /* 产品线ID */
	Description     string  `orm:"column(description);type(text);null" json:"description" form:"description"` /*产品描述内容  */
	DiscountId      int64     `orm:"column(discount_id)" json:"discount_id" form:"discount_id"`          /* 折扣ID */
	HaveGuarantee   bool    `orm:"column(have_guarantee)" json:"have_guarantee" form:"have_guarantee"` /* 是否有保修 */
	HaveInvoice     bool    `orm:"column(have_invoice)" json:"have_invoice" form:"have_invoice"`       /* 是否有发票 */
	ImageUrl        string  `orm:"column(image_url)" json:"image_url" form:"image_url"`           /* 图片对应的URL*/
	Name            string  `orm:"column(name);size(128);null" json:"name" form:"name"`            /*产品名称  */
	OuterId         string  `orm:"column(outer_id);size(128);null" json:"outer_id" form:"outer_id"` /*商家编码  */
	ItemsCount      int     `orm:"column(items_count)" json:"items_count" form:"items_count"` /* 下载人数 */
	OrdersCount     int     `orm:"column(orders_count)" json:"orders_count" form:"orders_count"` /* 累计采购次数 */
	PostageFast     float32 `orm:"column(postage_fast);digits(12);decimals(2)" json:"postage_fast" form:"postage_fast"` /* 快递费用*/
	PostageId       int64     `orm:"column(postage_id)" json:"postage_id" form:"postage_id"` /* 运费模板ID */
	PostageType     string  `orm:"column(postage_type);size(128);null" json:"postage_type" form:"postage_type"` /*运费类型：供应商承担、分销商承担  */
	Quantity        int     `orm:"column(quantity)" json:"quantity" form:"quantity"` /* 产品库存 */
	AlarmNumber     int     `orm:"column(alarm_number)" json:"alarm_number" form:"alarm_number"` /* 警戒库存 */
	Skus     []*FenxiaoSku  `orm:"reverse(many)" json:"skus" form:"-"`           /* sku*/
	SkuJson        string      `orm:"-" json:"-" form:"skus"`                                 /* 临时存放上传的订单sku*/
	StatusId       int32       `orm:"column(status_id);default(1)" json:"status_id" form:"status_id"`     /* 状态：1 正常、2 删除 */
	TradeType      string      `orm:"column(trade_type);size(64);null" json:"trade_type" form:"trade_type"` /*分销方式 */
	CreatedAt      time.Time   `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`   /* 创建时间 */
	CreatedAtStr   string      `orm:"-" json:"created_at" form:"-"`
	UpdatedAt      time.Time   `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"` 
	UpdatedAtStr   string      `orm:"-" json:"updated_at" form:"-"`
}

/* 分销产品SKU */
type FenxiaoSku struct {
    Id              int64   `orm:"column(id);pk;auto" json:"id" form:"id"`      /* SKU ID */
    CompanyId       int64     `orm:"column(company_id)" json:"company_id" form:"company_id"`    //供应商ID
	Pid             *FenxiaoProduct   `orm:"column(pid);rel(fk);on_delete(cascade)" json:"pid" form:"-"`  /* 产品ID */
	Name            string  `orm:"column(name);size(128);null" json:"name,omitempty" form:"name"`              /*名称  */
	OuterId         string  `orm:"column(outer_id);size(128);null" json:"outer_id,omitempty" form:"outer_id"`  /*商家编码  */
	ImageUrl        string  `orm:"column(image_url);size(128);null" json:"image_url,omitempty" form:"image_url"` /*图片对应的URL  */
	Properties      string  `orm:"column(properties);size(128);null" json:"properties,omitempty" form:"properties"` /*SKU销售属性组合字符串  */
	Quantity        int     `orm:"column(quantity)" json:"quantity,omitempty" form:"quantity"`                      /* 库存 */
	PurStandardPrice    float32 `orm:"column(pur_standard_price);digits(12);decimals(2)" json:"pur_standard_price,omitempty" form:"pur_standard_price"` /*采购基准价*/
    RetailStandardPrice float32 `orm:"column(retail_standard_price);digits(12);decimals(2)" json:"retail_standard_price,omitempty" form:"retail_standard_price"` /*零售基准价*/
	RetailPriceHigh float32 `orm:"column(retail_price_high);digits(12);decimals(2)" json:"retail_price_high,omitempty" form:"retail_price_high"` /*最高零售价*/
	RetailPriceLow  float32 `orm:"column(retail_price_low);digits(12);decimals(2)" json:"retail_price_low,omitempty" form:"retail_price_low"`    /*最低零售价*/
	StatusId        int32   `orm:"column(status_id);default(1)" json:"status_id,omitempty" form:"status_id"`     /* 状态：1 正常、2 删除 */
}

func init() {
    orm.RegisterModel(new(FenxiaoProduct),new(FenxiaoSku))   
}

func AddFenxiaoProduct(m *FenxiaoProduct) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddFenxiaoSku(m *FenxiaoSku) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddMultiFenxiaoSkus(list []*FenxiaoSku) (err error) {
	size := len(list)
	o := models.GetDefaultDB()
	if size > 1 {
	    _, err = o.InsertMulti(size, list) 
	}else{
	   _, err = o.Insert(list[0])
	}
	return
}

func GetFenxiaoProductById(id int64) (v *FenxiaoProduct, err error) {
	o := models.GetDefaultDB()
	v = &FenxiaoProduct{Pid: id}
	if err = o.Read(v); err == nil {
		o.LoadRelated(v, "Skus")
		for _, sku := range v.Skus {   
			sku.Pid = nil
		}
		return v, nil
	}
	return nil, err
}
func GetFenxiaoProductByOuterId(outerId string) (v *FenxiaoProduct, err error) {
	o := models.GetDefaultDB()
	v = &FenxiaoProduct{OuterId: outerId}
	if err = o.Read(v, "OuterId"); err == nil {
		o.LoadRelated(v, "Skus")
		for _, sku := range v.Skus {   
			sku.Pid = nil
		}
		return v, nil
	}
	return nil, err
}

func GetFenxiaoSkuBySkuId(id int64) (v *FenxiaoSku, err error) {
	o := models.GetDefaultDB()
	v = &FenxiaoSku{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllFenxiaoProducts(query map[string]string,fields []string,order_by map[string]string,offset,limit int)([]*FenxiaoProduct, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(FenxiaoProduct))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, ","); ok {
		    valueArr := strings.Split(v, ",")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}	
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*FenxiaoProduct
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
	    for _, product := range lists {
			o.LoadRelated(product, "Skus")
			for _, sku := range product.Skus {   
			    sku.Pid = nil
		    }
			product.CreatedAtStr = product.CreatedAt.Format(consts.DATETIME_FORMAT)
			product.UpdatedAtStr = product.UpdatedAt.Format(consts.DATETIME_FORMAT)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateFenxiaoProductById(m *FenxiaoProduct, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := FenxiaoProduct{Pid: m.Pid}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		if _, err = o.Update(m, k...); err != nil {
			return err
		}
	}
	return
}

func UpdateFenxiaoSkuBySkuId(m *FenxiaoSku, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := FenxiaoSku{Id: m.Id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m, k...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func UpdateFenxiaoProductByOuterId(m *FenxiaoProduct, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := FenxiaoProduct{OuterId: m.OuterId}
	if err = o.Read(&v, "OuterId"); err == nil {
		var num int64
		if num, err = o.Update(m, k...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func UpdateFenxiaoSkuByOuterId(m *FenxiaoSku, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := FenxiaoSku{OuterId: m.OuterId}
	if err = o.Read(&v, "OuterId"); err == nil {
		var num int64
		if num, err = o.Update(m, k...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func DeleteFenxiaoProductById(id int64) (err error) {
	o := models.GetDefaultDB()
	v := FenxiaoProduct{Pid: id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&v); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

func DeleteFenxiaoSkuBySkuId(id int64) (err error) {
	o := models.GetDefaultDB()
	v := FenxiaoSku{Id: id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&v); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}



